package cards.service;

import java.util.Date;
import java.util.Objects;

import cards.controller.ProfileController;
import cards.dao.UserDao;
import cards.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * 注册的service层
 * 
 * @author xiezhiping
 *
 */
@Service
public class RegisterService {
	@Autowired
	UserDao userDao;

	private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);

	@Autowired
	PasswordEncoder passwordEncoder;

	public String reg(String username, String password, String introduction, String nickname, int gender, String phoneNumber, int permission) {
		User user = new User();
		if (userDao.getUserByUsername(username) == null) {
			user.setUsername(username);
			user.setPassword(password);
			user.setPassword(passwordEncoder.encode(password));
			user.setNickname(nickname);
			user.setGender(gender);
			user.setPhoneNumber(phoneNumber);
			user.setPermission(permission);
			if (Objects.equals(introduction, "")) {
				user.setIntroduction(null);
			} else {
				user.setIntroduction(introduction);
			}
			user.setCreatedDate(new Date());
			userDao.addUser(user);
			return "/login";
		} else {
			return "/register";
		}
	}

	public String modify(Long id, String password, String introduction, String nickname, int gender, String phoneNumber) {

		userDao.updatePassword(id, passwordEncoder.encode(password));
		userDao.updateNickname(id, nickname);
		userDao.updateGender(id, gender);
		userDao.updatePhoneNumber(id, phoneNumber);
		userDao.updateIntroduction(id, introduction);
		logger.warn("modified profile success!");
		return "modifyprofile";
	}
}
